<?php

namespace app\http\controller\admin;

use Exception;
use mon\env\Config;
use GatewayClient\Gateway;
use app\model\ChatAppModel;
use app\model\ChatStayModel;
use app\model\ChatWaiterModel;
use app\model\ChatMessageModel;
use app\model\ChatVisitorModel;
use app\model\ChatMessageRelationModel;

/**
 * 管理端相关控制器
 */
class ChatController extends Controller
{
    /**
     * App管理
     *
     * @return string
     */
    public function app()
    {
        if ($this->request->isAjax()) {
            $data = ChatAppModel::instance()->queryList($this->request->get());
            return $this->success('ok', $data['list'], ['count' => $data['total']]);
        }
        return $this->fetch('chat/app');
    }

    /**
     * 新增应用
     *
     * @return string
     */
    public function appAdd()
    {
        if ($this->request->isPost()) {
            $save = ChatAppModel::instance()->add($this->request->post());
            if (!$save) {
                return $this->error(ChatAppModel::instance()->getError());
            }

            return $this->success('操作成功');
        }
        return $this->fetch('chat/appAdd');
    }

    /**
     * 编辑应用
     *
     * @param ChatAppModel $model
     * @return void
     */
    public function appEdit(ChatAppModel $model)
    {
        $idx = $this->request->get('idx', 0);
        $data = $model->getInfo(['id' => $idx]);
        if (!$data) {
            return $this->error($model->getError());
        }

        if ($this->request->isPost()) {
            $option = $this->request->post();
            $option['idx'] = $idx;
            $edit = $model->edit($option);
            if (!$edit) {
                return $this->error($model->getError());
            }

            return $this->success('操作成功');
        }

        return $this->fetch('chat/appEdit', ['info' => $data]);
    }

    /**
     * 应用状态
     *
     * @return string
     */
    public function appStatus()
    {
        $app = $this->request->get('app');
        if (!$app) {
            return $this->error('query faild');
        }

        try {
            Gateway::$registerAddress = Config::instance()->get('socket.gateway.registerAddress');
            // 获取在线客服
            $onLineKF = Gateway::getClientSessionsByGroup("kf_" . $app);
            // 获取在线访客
            $onLineChat = Gateway::getClientSessionsByGroup("chat_" . $app);
            // 获取在线等待访客
            $onLineWait = Gateway::getClientSessionsByGroup("wait_" . $app);
        } catch (Exception $e) {
            $onLineKF = [];
            $onLineChat = [];
            $onLineWait = [];
        }

        return $this->fetch('chat/appStatus', [
            'app' => $app,
            'onLineKF' => $onLineKF,
            'onLineChat' => $onLineChat,
            'onLineWait' => $onLineWait
        ]);
    }

    /**
     * 应用信息
     *
     * @param ChatAppModel $model
     * @return void
     */
    public function appInfo(ChatAppModel $model)
    {
        $idx = $this->request->get('idx', 0);
        $data = $model->getInfo(['id' => $idx]);

        return $this->fetch('chat/appInfo', ['info' => $data]);
    }

    /**
     * 查看留言
     *
     * @param ChatStayModel $model
     * @return void
     */
    public function stay(ChatStayModel $model)
    {
        if ($this->request->isAjax()) {
            $app = $this->request->get('app');
            if (!$app) {
                return $this->success('ok', [], ['count' => 0]);
            }
            $data = $model->queryList($this->request->get());
            return $this->success('ok', $data['list'], ['count' => $data['total']]);
        }
        return $this->fetch('chat/stay');
    }

    /**
     * 应用客服账号
     *
     * @param ChatWaiterModel $model
     * @return void
     */
    public function waiter(ChatWaiterModel $model)
    {
        $app_id = $this->request->get('app');
        if (!$app_id || !check('int', $app_id) || $app_id <= 0) {
            return $this->error('query faild');
        }
        if ($this->request->isAjax()) {
            $query = $this->request->get();
            $query['app_id'] = $app_id;
            $data = $model->queryList($query);
            return $this->success('ok', $data['list'], ['count' => $data['total']]);
        }

        $this->assign('app_id', $app_id);
        return $this->fetch('chat/waiter');
    }

    /**
     * 编辑客服账号
     *
     * @param ChatWaiterModel $model
     * @return void
     */
    public function waiterEdit(ChatWaiterModel $model)
    {
        $idx = $this->request->get('idx', 0);
        $data = $model->getInfo(['id' => $idx]);
        if (!$data) {
            return $this->error($model->getError());
        }

        if ($this->request->isPost()) {
            $option = $this->request->post();
            $option['idx'] = $idx;
            $edit = $model->edit($option);
            if (!$edit) {
                return $this->error($model->getError());
            }

            return $this->success('操作成功');
        }
        return $this->fetch('chat/waiterEdit', ['info' => $data]);
    }

    /**
     * 新增客服
     *
     * @param ChatWaiterModel $model
     * @return void
     */
    public function waiterAdd(ChatWaiterModel $model)
    {
        $app_id = $this->request->get('app');
        if (!$app_id || !check('int', $app_id) || $app_id <= 0) {
            return $this->error('query faild');
        }
        if ($this->request->isPost()) {
            $save = $model->add($this->request->post());
            if (!$save) {
                return $this->error($model->getError());
            }

            return $this->success('操作成功');
        }
        $this->assign('app_id', $app_id);
        return $this->fetch('chat/waiterAdd');
    }

    /**
     * 历史记录
     *
     * @param ChatMessageRelationModel $model
     * @return void
     */
    public function history(ChatMessageRelationModel $model)
    {
        if ($this->request->isAjax()) {
            $query = $this->request->get();
            $data = $model->getList($query);
            return $this->success('ok', $data['list'], ['count' => $data['total']]);
        }
        return $this->fetch('chat/history');
    }

    /**
     * 通信记录
     *
     * @param ChatMessageModel $message
     * @param ChatMessageRelationModel $messageRelation
     * @return void
     */
    public function historyInfo(ChatMessageModel $message, ChatMessageRelationModel $messageRelation)
    {
        $idx = $this->request->get('idx', 0);
        $info = $messageRelation->where(['id' => $idx])->get();
        if ($info->isEmpty()) {
            return $this->error('query faild');
        }
        $data = $message->getMessage($idx);

        return $this->fetch('chat/historyInfo', [
            'info'  => $info->toArray(),
            'list'  => json_encode($data, JSON_UNESCAPED_UNICODE)
        ]);
    }

    /**
     * 查看游客信息
     *
     * @param ChatVisitorModel $model
     * @return void
     */
    public function visit(ChatVisitorModel $model)
    {
        $visitID = $this->request->get('visitid');
        $info = $model->getInfo(['visitid' => $visitID]);
        if (!$info) {
            return $this->error($model->getError(), 200);
        }
        if ($this->request->isPost()) {
            $option = $this->request->post();
            // 移除空参数
            foreach ($option as $k => $v) {
                if ($v === '') {
                    unset($option[$k]);
                }
            }
            $save = $model->modify($option, $visitID);
            if (!$save) {
                return $this->error($model->getError());
            }

            return $this->success('操作成功');
        }

        return $this->fetch('chat/visit', ['info' => $info]);
    }
}
